import React, { useEffect, useState } from 'react';
import { Checkbox, Descriptions, Divider, Input, Radio, Space, Tooltip } from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import styles from './component.module.less';
import appWorkState from './store';
import { useSnapshot } from 'valtio';
import appState from '../sotre';

export interface SubWorkItem {
  ITEM_DESC: string;
  ITEM_NUM: string;
  ITEM_ID: string;
  ITEM_TYPE: string;
  ITEM_CNAME: string;
  WORK_ID: string;
  ITEM_CODE: string;
  ITEM_CLASS: string;
  ITEM_SORT: string;
  PChildWorkItemOption: {
    OPTION_ID: string;
    OPTION_NAME: string;
    REF_VALUE: string;
  }[];
}
export interface WorkItem {
  WORK_NUM: string;
  WORK_ID: string;
  WORK_NAME: string;
  MAX_SERT: string;
  pchildWorkForm: SubWorkItem[];
}
const CheckboxGroup = Checkbox.Group;

const CheckItem = (props: { itemInfo: WorkItem }) => {
  const { itemInfo } = props;
  const workStore = useSnapshot(appWorkState);
  const { currentItemTitleId } = workStore;

  const [checkedList, _setCheckedList] = useState<any[]>([]);
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(false);

  // const [currentSelId, setCurrentSelId] = useState<string>();
  // const [currentWorkId, setCurrentWorkId] = useState<string>();

  const setCheckedList = (list: string[]) => {
    appWorkState.currentItemKeyList = list;
    _setCheckedList(list);
  };

  const onChange = (list: string[]) => {
    // console.log(list);
    setCheckedList(list);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    const selList = itemInfo?.pchildWorkForm?.map((v) => v.ITEM_ID);
    setCheckedList(e.target.checked ? selList : []);
    setIndeterminate(!(selList.length === itemInfo.pchildWorkForm?.length || selList.length === 0));
  };

  useEffect(() => {
    if (!checkedList.length) {
      setCheckAll(false);
    }
    if (checkedList.length && checkedList.length !== itemInfo.pchildWorkForm?.length) {
      setIndeterminate(true);
      return;
    }
    setIndeterminate(false);
  }, [checkedList]);
  // 处理未选
  useEffect(() => {
    if (!appWorkState.currentItemKeyList) {
      return;
    }
    const str1 = appWorkState.currentItemKeyList.toString();
    const str2 = checkedList.toString();
    if (str1 !== str2) {
      _setCheckedList([]);
    }
  }, [appWorkState.currentItemKeyList]);

  return (
    <div key={itemInfo.WORK_ID}>
      <div
        className={styles.work}
        style={{
          backgroundColor: appWorkState.currentWorkId === itemInfo.WORK_ID ? '#ffd666' : '#EDF4FF',
        }}
        onClick={() => {
          console.log('click', itemInfo.WORK_ID);
          appWorkState.currentWorkId = itemInfo.WORK_ID;
          appWorkState.currentItemTitleId = undefined;
        }}
      >
        <Checkbox
          onClick={(e) => {
            setCheckAll(!checkAll);
          }}
          indeterminate={indeterminate}
          onChange={onCheckAllChange}
          checked={checkAll}
        />
        <div style={{ whiteSpace: 'nowrap', cursor: 'pointer' }}>
          {itemInfo?.WORK_NUM}, {itemInfo?.WORK_NAME}
        </div>
      </div>

      <CheckboxGroup
        style={{ display: 'flex', flexDirection: 'column', gap: '2px,2px' }}
        // value={checkedList}
        value={workStore.currentItemKeyList as any}
        onChange={(v) => onChange(v as string[])}
      >
        {itemInfo?.pchildWorkForm?.map((sub, subIndex) => {
          return (
            <div
              key={sub.ITEM_ID + subIndex}
              className={styles.item}
              style={{
                backgroundColor: currentItemTitleId === sub?.ITEM_ID ? '#fff1b8' : '#fff',
              }}
              onClick={() => {
                appWorkState.currentItemTitleId = sub.ITEM_ID;
                appWorkState.currentWorkId = itemInfo.WORK_ID;
                const itemCodeNum = sub.ITEM_CODE?.split('_');
                appState.factory.jumpToBookMark(`SO_${itemCodeNum.pop()}`);
              }}
            >
              <Space size={4}>
                <Checkbox value={sub.ITEM_ID} key={sub.ITEM_ID} />
                <div style={{ minHeight: 24 }}>
                  {subIndex + 1}. {sub.ITEM_CNAME}
                </div>
              </Space>

              <Space size={0}>
                <Divider type="vertical" />
                <div className={styles['right_item']}>
                  {sub.ITEM_TYPE === 'CO' && (
                    <Radio.Group style={{ display: 'flex', gap: 0 }}>
                      {sub?.PChildWorkItemOption?.map((v) => {
                        return (
                          <Radio key={v.OPTION_ID} value={v.OPTION_ID} className={styles['radio']}>
                            <div title={v.OPTION_NAME} className={styles['txt']}>
                              {v.OPTION_NAME}
                            </div>
                          </Radio>
                        );
                      })}
                    </Radio.Group>
                  )}
                  {sub.ITEM_TYPE === 'PO' && <Input placeholder="填写" size="small" />}
                  {sub.ITEM_TYPE === 'EO' && (
                    <Tooltip title={sub?.ITEM_DESC}>
                      <span>{sub?.ITEM_DESC}</span>
                    </Tooltip>
                  )}
                </div>
              </Space>
            </div>
          );
        })}
      </CheckboxGroup>
    </div>
  );
};

const CheckItemContent = (props: { itemList?: WorkItem[] }) => {
  const { itemList } = props;
  return (
    <>
      {itemList?.map((item) => {
        return <CheckItem key={item.WORK_ID} itemInfo={item} />;
      })}
    </>
  );
};

export { CheckItemContent };
